﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.RunningSimulation.SimulationRunner
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using EngineeringInternalExtension;
using Microsoft.Win32;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Threading;
using System.Windows.Forms;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.PrivateImplementationDetails;


namespace DnProcessSimulateCommands.RunningSimulation;

public class SimulationRunner
{
  public bool m_writeTimeInLogForSignal = true;
  private const double RTEpsilonD = 1E-06;
  private CultureInfo m_origCulture = Thread.CurrentThread.CurrentCulture;
  private bool m_useCustomSimulationPlayer;
  private ArrayList m_ObjsData = new ArrayList();
  private TxSimulationPlayer m_simulationPlayer;
  private double m_timeToRecord;
  private List<string> m_linesToWrite = new List<string>();
  private double m_lastTimeFlushed = -1.0;
  private List<SignalData> m_signalValues = new List<SignalData>();
  private SimulationFileAccessor m_fileAccessor;
  private readonly int m_numOfDigitsForCurrentTime = 4;
  private readonly int m_numOfDigitsForCurrentTranslation = 3;
  private readonly int m_numOfDigitsForCurrentRotation = 4;
  private readonly int m_numOfDigitsForCurrentJoint = 3;

  public bool startRecording(string filePath, string time, SimulationFileAccessor fileAccessor)
  {
    if (Thread.CurrentThread.CurrentCulture.Name != "en-US")
      Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
    bool flag = false;
    try
    {
      if (this.HasFileName(filePath))
      {
        if (this.HasTime(time))
        {
          this.m_fileAccessor = fileAccessor;
          int length = filePath.LastIndexOf("\\");
          if (length > -1)
          {
            string path = filePath.Substring(0, length);
            if (!Directory.Exists(path))
              Directory.CreateDirectory(path);
          }
          this.m_fileAccessor.openFile(filePath);
          this.RunSimulation(Convert.ToDouble(time));
          flag = true;
        }
      }
    }
    catch (Exception ex)
    {
      int num = (int) TxMessageBox.Show($"{ex.Message} \n{ex.StackTrace}", "SimulationRecorder Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
    return flag;
  }

  public void setCustomSimulationPlayer(TxSimulationPlayer player)
  {
    this.m_simulationPlayer = player;
    this.m_useCustomSimulationPlayer = true;
    this.RegisterSimulationEvents();
  }

  public void RunSimulation(double time)
  {
    this.m_timeToRecord = time;
    if (!this.m_useCustomSimulationPlayer)
      this.RegisterSimulationEvents();
    this.PrintHeader();
    foreach (ITxObject allDescendant in (Collection<ITxObject>) TxApplication.ActiveDocument.PhysicalRoot.GetAllDescendants((ITxTypeFilter) new TxTypeFilter(new Type[3]
    {
      typeof (ITxComponent),
      typeof (ITxDevice),
      typeof (ITxLocationOperation)
    }, new Type[0])))
      this.addObj(allDescendant);
    foreach (ITxObject signal1 in (Collection<ITxObject>) TxApplication.ActiveDocument.PlcProgramRoot.CurrentPlcProgram.GetSignals((ITxTypeFilter) new TxTypeFilter(typeof (ITxPlcSignal))))
    {
      ITxPlcSignal signal2 = signal1 as ITxPlcSignal;
      this.m_signalValues.Add(new SignalData(signal2, (TxPlcHardwareType) signal2.DataType));
    }
  }

  public void stopRecording()
  {
    this.UnregisterSimulationEvents();
    this.SortAndWrite();
    if (this.m_fileAccessor is SimulationFileComparer)
      (this.m_fileAccessor as SimulationFileComparer).VerifyEndOFBaseLineContent();
    this.m_fileAccessor.closeFile();
    Thread.CurrentThread.CurrentCulture = this.m_origCulture;
  }

  private void addObj(ITxObject obj)
  {
    this.m_ObjsData.Add((object) new ObjData()
    {
      Obj = obj,
      LastLocation = new Tuple<double, TxTransformation>(-1.0, new TxTransformation()),
      LastVisibilityState = new Tuple<double, TxDisplayableObjectVisibility>(-1.0, (TxDisplayableObjectVisibility) 0),
      LastJointValues = new Tuple<double, ArrayList>(-1.0, new ArrayList())
    });
  }

  private void m_simulationPlayer_TimeIntervalReached(
    object sender,
    TxSimulationPlayer_TimeIntervalReachedEventArgs args)
  {
    try
    {
      if (this.m_timeToRecord > 0.0 && args.CurrentTime >= this.m_timeToRecord)
      {
        this.stopRecording();
      }
      else
      {
        ArrayList arrayList = new ArrayList();
        foreach (ObjData objData in this.m_ObjsData)
        {
          if (objData.Obj.IsValid())
          {
            this.checkLocations(objData, args);
            this.checkVisibility(objData, args);
            this.checkJoints(objData, args);
          }
          else
            arrayList.Add((object) objData);
        }
        this.m_ObjsData.Remove((object) arrayList);
        this.checkSignals(args);
        this.checkCollisions(args);
      }
    }
    catch (Exception ex)
    {
      int num = (int) TxMessageBox.Show($"{ex.Message} \n{ex.StackTrace}", "SimulationRecorder Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }

  private void m_simulationPlayer_OperationEndedForward(
    object sender,
    TxSimulationPlayer_OperationEndedForwardEventArgs args)
  {
    try
    {
      this.writeToFile($"[{this.TimeToTruncatedString(this.m_simulationPlayer.CurrentTime)}]: Operation: {((ITxObject) args.Operation).Name} ended. Total duration was: [{this.TimeToTruncatedString(args.Operation.Duration)}]");
    }
    catch (Exception ex)
    {
      int num = (int) TxMessageBox.Show($"{ex.Message} \n{ex.StackTrace}", "SimulationRecorder Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }

  private void m_simulationPlayer_OperationReachedDestination(
    object sender,
    TxSimulationPlayer_OperationReachedDestinationEventArgs args)
  {
    try
    {
      this.writeToFile($"[{this.TimeToTruncatedString(this.m_simulationPlayer.CurrentTime)}]: location: {((ITxObject) args.Operation).Name} reached");
    }
    catch (Exception ex)
    {
      int num = (int) TxMessageBox.Show($"{ex.Message} \n{ex.StackTrace}", "SimulationRecorder Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }

  private void m_simulationPlayer_OperationStartedForward(
    object sender,
    TxSimulationPlayer_OperationStartedForwardEventArgs args)
  {
    try
    {
      this.writeToFile($"[{this.TimeToTruncatedString(this.m_simulationPlayer.CurrentTime)}]: Operation: {((ITxObject) args.Operation).Name} started");
    }
    catch (Exception ex)
    {
      int num = (int) TxMessageBox.Show($"{ex.Message} \n{ex.StackTrace}", "SimulationRecorder Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }

  private void locObj_AttachmentParentChanged(
    object sender,
    TxLocatableObject_AttachmentParentChangedEventArgs args)
  {
    try
    {
      this.writeToFile($"[{this.TimeToTruncatedString(this.m_simulationPlayer.CurrentTime)}]: The attachment parent of: {((ITxObject) (sender as ITxLocatableObject)).Name} was changed");
    }
    catch (Exception ex)
    {
      int num = (int) TxMessageBox.Show($"{ex.Message} \n{ex.StackTrace}", "SimulationRecorder Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }

  private void locObj_AttachmentChildRemoved(
    object sender,
    TxLocatableObject_AttachmentChildRemovedEventArgs args)
  {
    try
    {
      this.writeToFile($"[{this.TimeToTruncatedString(this.m_simulationPlayer.CurrentTime)}]: The attachment child of: {((ITxObject) (sender as ITxLocatableObject)).Name} was removed");
    }
    catch (Exception ex)
    {
      int num = (int) TxMessageBox.Show($"{ex.Message} \n{ex.StackTrace}", "SimulationRecorder Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }

  private void locObj_AttachmentChildAdded(
    object sender,
    TxLocatableObject_AttachmentChildAddedEventArgs args)
  {
    try
    {
      this.writeToFile($"[{this.TimeToTruncatedString(this.m_simulationPlayer.CurrentTime)}]: The object: {((ITxObject) (sender as ITxLocatableObject)).Name} has a new attachment child: {((ITxObject) args.AttachmentChild).Name}");
    }
    catch (Exception ex)
    {
      int num = (int) TxMessageBox.Show($"{ex.Message} \n{ex.StackTrace}", "SimulationRecorder Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }

  private void PhysicalRoot_ItemCreated(object sender, TxObjectRoot_ItemCreatedEventArgs args)
  {
    try
    {
      if (args.Item is ITxPartAppearance)
      {
        this.writeToFile($"[{this.TimeToTruncatedString(this.m_simulationPlayer.CurrentTime)}]: Part Appearance: {args.Item.Name} was created!");
        this.addObj(args.Item);
      }
      else
      {
        if (!TxEngineeringDataInternal.ObjectIsResourceAppearance(args.Item))
          return;
        this.writeToFile($"[{this.TimeToTruncatedString(this.m_simulationPlayer.CurrentTime)}]: Resource Appearance: {args.Item.Name} was created!");
        this.addObj(args.Item);
      }
    }
    catch (Exception ex)
    {
      int num = (int) TxMessageBox.Show($"{ex.Message} \n{ex.StackTrace}", "SimulationRecorder Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }

  private void m_simulationPlayer_SimulationStopped(
    object sender,
    TxSimulationPlayer_SimulationStoppedEventArgs args)
  {
  }

  private void checkCollisions(
    TxSimulationPlayer_TimeIntervalReachedEventArgs args)
  {
    try
    {
      TxCollisionRoot collisionRoot = TxApplication.ActiveDocument.CollisionRoot;
      using (TxCollisionQueryResults objectsAndDistances = collisionRoot.GetCollidingObjectsAndDistances(new TxCollisionAndDistancesQueryParams()
      {
        Mode = collisionRoot.CollisionQueryMode,
        NearMissDistance = collisionRoot.NearMissDefaultValue,
        AllowedPenetration = (double) TxApplication.Options.Collision.ContactTolerance,
        UseAllowedPenetration = TxApplication.Options.Collision.CheckContact,
        UseNearMiss = collisionRoot.CheckNearMiss,
        FindPenetrationRegions = TxApplication.Options.Collision.FindPenetrationRegions,
        ReportLevel = TxApplication.Options.Collision.ReportLevel
      }))
      {
        foreach (TxCollisionState state in objectsAndDistances.States)
        {
          TxCollisionState.TxCollisionStateType type = state.Type;
          if (type - 2 <= 1 || type == 5)
          {
            ArrayList arrayList = new ArrayList();
            arrayList.Add((object) state.FirstObject.Name);
            arrayList.Add((object) state.SecondObject.Name);
            arrayList.Sort();
            this.m_fileAccessor.accessFile($"[{this.TimeToTruncatedString(args.CurrentTime)}]: {state.Type.ToString()} between {arrayList[0]?.ToString()} and {arrayList[1]?.ToString()}");
          }
          ((TxDisposable) state).Dispose();
        }
      }
    }
    catch (Exception ex)
    {
      int num = (int) TxMessageBox.Show($"{ex.Message} \n{ex.StackTrace}", "SimulationRecorder Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }

  private void checkSignals(
    TxSimulationPlayer_TimeIntervalReachedEventArgs args)
  {
    try
    {
      foreach (SignalData signalValue in this.m_signalValues)
      {
        if (signalValue.isSignalValueChanged())
        {
          signalValue.SetValue(signalValue.Signal.Value.GetValueByType(signalValue.Type));
          string str = signalValue.Signal.Value.GetValueByType(signalValue.Type).ToString();
          string line;
          if (this.m_writeTimeInLogForSignal)
            line = $"[{this.TimeToTruncatedString(args.CurrentTime)}]: Signal value for {((ITxObject) signalValue.Signal).Name} changed to {str}";
          else
            line = $": Signal value for {((ITxObject) signalValue.Signal).Name} changed to {str}";
          this.m_fileAccessor.accessFile(line);
        }
      }
    }
    catch (Exception ex)
    {
      int num = (int) TxMessageBox.Show($"{ex.Message} \n{ex.StackTrace}", "SimulationRecorder Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }

  private void checkJoints(
    ObjData objData,
    TxSimulationPlayer_TimeIntervalReachedEventArgs args)
  {
    try
    {
      if (!(objData.Obj is ITxDevice itxDevice))
        return;
      bool flag = false;
      if (itxDevice.CurrentPose.JointValues.Count != objData.LastJointValues.Item2.Count)
        flag = true;
      for (int index = 0; index < itxDevice.CurrentPose.JointValues.Count && !flag; ++index)
        flag = Math.Abs((double) objData.LastJointValues.Item2[index] - (double) itxDevice.CurrentPose.JointValues[index]) > 1E-06;
      if (!flag)
        return;
      objData.LastJointValues = new Tuple<double, ArrayList>(args.CurrentTime, itxDevice.CurrentPose.JointValues);
      string str = $"[{this.TxPoseDataToTruncatedString(itxDevice.CurrentPose)}]";
      this.writeToFile($"[{this.TimeToTruncatedString(args.CurrentTime)}]: Joints for Device: {objData.Obj.Name} moved to: {str}");
    }
    catch (Exception ex)
    {
      int num = (int) TxMessageBox.Show($"{ex.Message} \n{ex.StackTrace}", "SimulationRecorder Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }

  private void checkVisibility(
    ObjData objData,
    TxSimulationPlayer_TimeIntervalReachedEventArgs args)
  {
    try
    {
      if (!(objData.Obj is ITxDisplayableObject displayableObject) || objData.LastVisibilityState.Item2 == displayableObject.Visibility)
        return;
      objData.LastVisibilityState = new Tuple<double, TxDisplayableObjectVisibility>(args.CurrentTime, displayableObject.Visibility);
      string str = "";
      if (objData.Obj is ITxRobot)
        str = "The Robot";
      else if (objData.Obj is ITxDevice)
        str = "The Device";
      else if (objData.Obj is ITxPartAppearance)
        str = "The Part Appearance";
      else if (objData.Obj is ITxComponent)
        str = "The Component";
      else if (objData.Obj is ITxLocationOperation)
        str = "The Location Operation";
      this.writeToFile($"[{this.TimeToTruncatedString(args.CurrentTime)}]: {str}: {objData.Obj.Name} visibility state changed to: {displayableObject.Visibility.ToString()}");
    }
    catch (Exception ex)
    {
      int num = (int) TxMessageBox.Show($"{ex.Message} \n{ex.StackTrace}", "SimulationRecorder Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }

  private void checkLocations(
    ObjData objData,
    TxSimulationPlayer_TimeIntervalReachedEventArgs args)
  {
    try
    {
      if (!(objData.Obj is ITxLocatableObject itxLocatableObject))
        return;
      TxTransformation trans = !(objData.Obj is ITxRobot) ? itxLocatableObject.AbsoluteLocation : (objData.Obj as TxRobot).TCPF.AbsoluteLocation;
      if (!TxTransformation.op_Inequality(objData.LastLocation.Item2, trans))
        return;
      objData.LastLocation = new Tuple<double, TxTransformation>(args.CurrentTime, trans);
      string str = "";
      if (objData.Obj is ITxRobot)
        str = "TCPF for Robot";
      else if (objData.Obj is ITxDevice)
        str = "The Device";
      else if (objData.Obj is ITxPartAppearance)
        str = "The Part Appearance";
      else if (objData.Obj is ITxComponent)
        str = "The Component";
      else if (objData.Obj is ITxLocationOperation)
        str = "The Location Operation";
      this.TxTransformationToTruncatedString(trans);
      this.writeToFile($"[{this.TimeToTruncatedString(args.CurrentTime)}]: {str}: {objData.Obj.Name} moved to {this.TxTransformationToTruncatedString(trans)}");
    }
    catch (Exception ex)
    {
      int num = (int) TxMessageBox.Show($"{ex.Message} \n{ex.StackTrace}", "SimulationRecorder Error", MessageBoxButtons.OK, MessageBoxIcon.Hand);
    }
  }

  private string TxTransformationToTruncatedString(TxTransformation trans)
  {
    return $"{$"Translation: [{this.TranslationToString(trans, this.m_numOfDigitsForCurrentTranslation)}]"} Rotation: [{this.RotationToString(trans, this.m_numOfDigitsForCurrentRotation)}]";
  }

  private string DoubleFormat(double num, int decimalDigit)
  {
    string format = "f" + decimalDigit.ToString();
    string str = num.ToString(format);
    if (str.Contains("."))
      str = str.TrimEnd('0');
    if (str.EndsWith("."))
      str = str.TrimEnd('.');
    return str;
  }

  internal string TimeToTruncatedString(double time)
  {
    return this.DoubleFormat(Math.Round(time, this.m_numOfDigitsForCurrentTime), this.m_numOfDigitsForCurrentTime);
  }

  internal string TxPoseDataToTruncatedString(TxPoseData pose)
  {
    string str = "";
    foreach (double jointValue in pose.JointValues)
    {
      str += this.DoubleFormat(Math.Round(jointValue, this.m_numOfDigitsForCurrentJoint), this.m_numOfDigitsForCurrentJoint);
      str += ", ";
    }
    return str.Remove(str.Length - 2);
  }

  internal string RotationToString(TxTransformation trans, int precision)
  {
    string str = "";
    for (int index1 = 0; index1 < 3; ++index1)
    {
      for (int index2 = 0; index2 < 3; ++index2)
        str = str + this.DoubleFormat(Math.Round(trans[index1, index2], precision), precision) + ", ";
    }
    return str.Remove(str.Length - 2);
  }

  internal string TranslationToString(TxTransformation trans, int precision)
  {
    string str = "";
    for (int index = 0; index < 3; ++index)
      str = str + this.DoubleFormat(Math.Round(trans[index, 3], precision), precision) + ", ";
    return str.Remove(str.Length - 2);
  }

  private void RegisterSimulationEvents()
  {
    if (this.m_simulationPlayer == null)
      this.m_simulationPlayer = TxApplication.ActiveDocument.SimulationPlayer;
    this.m_simulationPlayer.TimeIntervalReached += new TxSimulationPlayer_TimeIntervalReachedEventHandler(this.m_simulationPlayer_TimeIntervalReached);
    this.m_simulationPlayer.OperationEndedForward += new TxSimulationPlayer_OperationEndedForwardEventHandler(this.m_simulationPlayer_OperationEndedForward);
    this.m_simulationPlayer.OperationReachedDestination += new TxSimulationPlayer_OperationReachedDestinationEventHandler(this.m_simulationPlayer_OperationReachedDestination);
    this.m_simulationPlayer.OperationStartedForward += new TxSimulationPlayer_OperationStartedForwardEventHandler(this.m_simulationPlayer_OperationStartedForward);
    this.m_simulationPlayer.SimulationStopped += new TxSimulationPlayer_SimulationStoppedEventHandler(this.m_simulationPlayer_SimulationStopped);
    TxApplication.ActiveDocument.PhysicalRoot.ItemCreated += new TxObjectRoot_ItemCreatedEventHandler(this.PhysicalRoot_ItemCreated);
    foreach (ITxLocatableObject allDescendant in (Collection<ITxObject>) TxApplication.ActiveDocument.PhysicalRoot.GetAllDescendants((ITxTypeFilter) new TxTypeFilter(typeof (ITxLocatableObject))))
    {
      allDescendant.AttachmentChildAdded += new TxLocatableObject_AttachmentChildAddedEventHandler(this.locObj_AttachmentChildAdded);
      allDescendant.AttachmentChildRemoved += new TxLocatableObject_AttachmentChildRemovedEventHandler(this.locObj_AttachmentChildRemoved);
      allDescendant.AttachmentParentChanged += new TxLocatableObject_AttachmentParentChangedEventHandler(this.locObj_AttachmentParentChanged);
    }
  }

  private void UnregisterSimulationEvents()
  {
    if (this.m_simulationPlayer == null)
      this.m_simulationPlayer = TxApplication.ActiveDocument.SimulationPlayer;
    this.m_simulationPlayer.TimeIntervalReached -= new TxSimulationPlayer_TimeIntervalReachedEventHandler(this.m_simulationPlayer_TimeIntervalReached);
    this.m_simulationPlayer.OperationEndedForward -= new TxSimulationPlayer_OperationEndedForwardEventHandler(this.m_simulationPlayer_OperationEndedForward);
    this.m_simulationPlayer.OperationReachedDestination -= new TxSimulationPlayer_OperationReachedDestinationEventHandler(this.m_simulationPlayer_OperationReachedDestination);
    this.m_simulationPlayer.OperationStartedForward -= new TxSimulationPlayer_OperationStartedForwardEventHandler(this.m_simulationPlayer_OperationStartedForward);
    this.m_simulationPlayer.SimulationStopped -= new TxSimulationPlayer_SimulationStoppedEventHandler(this.m_simulationPlayer_SimulationStopped);
    TxApplication.ActiveDocument.PhysicalRoot.ItemCreated -= new TxObjectRoot_ItemCreatedEventHandler(this.PhysicalRoot_ItemCreated);
    foreach (ITxLocatableObject allDescendant in (Collection<ITxObject>) TxApplication.ActiveDocument.PhysicalRoot.GetAllDescendants((ITxTypeFilter) new TxTypeFilter(typeof (ITxLocatableObject))))
    {
      allDescendant.AttachmentChildAdded -= new TxLocatableObject_AttachmentChildAddedEventHandler(this.locObj_AttachmentChildAdded);
      allDescendant.AttachmentChildRemoved -= new TxLocatableObject_AttachmentChildRemovedEventHandler(this.locObj_AttachmentChildRemoved);
      allDescendant.AttachmentParentChanged -= new TxLocatableObject_AttachmentParentChangedEventHandler(this.locObj_AttachmentParentChanged);
    }
    this.m_simulationPlayer = (TxSimulationPlayer) null;
    this.m_useCustomSimulationPlayer = false;
  }

  private void writeToFile(string newLine)
  {
    if (this.m_simulationPlayer.CurrentTime <= this.m_lastTimeFlushed)
    {
      this.m_linesToWrite.Add(newLine);
    }
    else
    {
      this.SortAndWrite();
      this.m_lastTimeFlushed = this.m_simulationPlayer.CurrentTime;
      this.m_linesToWrite.Add(newLine);
    }
  }

  private void SortAndWrite()
  {
    this.m_linesToWrite.Sort();
    foreach (string line in this.m_linesToWrite)
      this.m_fileAccessor.accessFile(line);
    this.m_linesToWrite.Clear();
  }

  private bool HasFileName(string filePath)
  {
    bool flag = filePath != "";
    if (!flag)
    {
      int num = (int) TxMessageBox.Show("To start generating a report make sure that a file path is set.", "Simulation Recorder", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
    }
    return flag;
  }

  private bool HasTime(string time)
  {
    bool flag = time != "";
    if (!flag)
    {
      int num = (int) TxMessageBox.Show("To start generating a report make sure that a time is set.", "Simulation Recorder", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
    }
    return flag;
  }

  private void PrintHeader()
  {
    this.m_fileAccessor.accessFile("New recording:", true);
    this.m_fileAccessor.accessFile("# The version in which this log was created is: " + FileVersionInfo.GetVersionInfo(this.getRegistryStringValue(Registry.LocalMachine, "SOFTWARE\\Tecnomatix\\eMPower", "eMPowerDir") + "\\DotNetCommands\\DnProcessSimulateCommands.dll").FileVersion, true);
    this.m_fileAccessor.accessFile("# Recorded on: " + DateTime.Now.ToString(), true);
    this.m_fileAccessor.accessFile("# The Time Interval is: " + TxApplication.ActiveDocument.SimulationPlayer.TimeInterval.ToString(), true);
    this.m_fileAccessor.accessFile(!((Collection<ITxObject>) TxApplication.ActiveDocument.OperationRoot.GetAllDescendants((ITxTypeFilter) new TxNoTypeFilter()))[0].Name.Equals("LineOperation") ? "# Running in Standard mode" : "# Running in Line Simulation mode", true);
    this.m_fileAccessor.accessFile("# ignoringOLPCommands = " + TxApplication.Options.Simulation.IgnoreRobotLogic.ToString(), true);
    this.m_fileAccessor.accessFile("# ignoreSignals = " + TxApplication.Options.Simulation.IgnoreSignals.ToString(), true);
    this.m_fileAccessor.accessFile("# Number of decimal places for translation data = " + this.m_numOfDigitsForCurrentTranslation.ToString(), true);
    this.m_fileAccessor.accessFile("# Number of decimal places for rotation matrix data = " + this.m_numOfDigitsForCurrentRotation.ToString(), true);
    this.m_fileAccessor.accessFile("# Number of decimal places for joint data = " + this.m_numOfDigitsForCurrentJoint.ToString(), true);
    this.m_fileAccessor.accessFile("# Number of decimal places for current time = " + this.m_numOfDigitsForCurrentTime.ToString(), true);
    this.m_fileAccessor.accessFile("", true);
    this.m_fileAccessor.accessFile(!TxApplicationEx.DoesKinUseDoubles() ? "# The kinematics use floats (:-( " : "# The kinematics use (:-) doubles ", true);
    this.m_fileAccessor.accessFile("", true);
    this.m_fileAccessor.accessFile("Collision Options:", true);
    this.m_fileAccessor.accessFile("# CheckContact = " + TxApplication.Options.Collision.CheckContact.ToString(), true);
    this.m_fileAccessor.accessFile("# CheckNearMiss = " + TxApplication.Options.Collision.CheckNearMiss.ToString(), true);
    this.m_fileAccessor.accessFile("# NearMissDefaultValue = " + TxApplication.Options.Collision.NearMissDefaultValue.ToString(), true);
    this.m_fileAccessor.accessFile("# ContactTolerance = " + TxApplication.Options.Collision.ContactTolerance.ToString(), true);
    this.m_fileAccessor.accessFile("# StopOnCollision = " + TxApplication.Options.Collision.StopOnCollision.ToString(), true);
    this.m_fileAccessor.accessFile("", true);
    this.m_fileAccessor.accessFile("The Simulation:", true);
  }

  public string getRegistryStringValue(RegistryKey regType, string keyName, string valueName)
  {
    string registryStringValue = "";
    RegistryKey registryKey = regType.OpenSubKey(keyName);
    if (registryKey != null)
      registryStringValue = registryKey.GetValue(valueName).ToString();
    return registryStringValue;
  }
}
